package com.matrix.draft.sockettest.day6.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

// 默认Handler
public class DefaultChannelHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

    }

    // 读取
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println(ctx.channel().remoteAddress() + " : " + buf.toString(CharsetUtil.UTF_8));

    }

    // 读完之后
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("恭喜你,业务执行成功!", CharsetUtil.UTF_8));
        ctx.executor().execute(() -> {
            try {
                Thread.sleep(3 * 1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer(ctx.channel().remoteAddress() + "的邮箱到了!", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    // 当出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
